import { nextTick, onMounted, ref, type Ref, watch } from 'vue';

/**
 * 根据id获取元素高度  =id高度-变化元素高度-要减去的高度
 *
 * @param elementRef 变化的元素 不传时获取元素高度
 * @param resizeHeightOffset  要减去的高度 不传时获取元素高度
 */
export function useHeight(id: string, elementRef?: Ref, resizeHeightOffset = 0) {
  const returnHeight = ref<number>(0);
  let windowHeight: any = 0;

  onMounted(() => {
    windowHeight = document.getElementById(id)?.offsetHeight;
    // console.log('windowHeight', windowHeight);
    redoHeight();
  });
  watch(
    () => elementRef,
    () => {
      redoHeight();
    },
    {
      deep: true,
    },
  );

  //重新计算高度
  function redoHeight() {
    const offset = resizeHeightOffset ? resizeHeightOffset : 0;
    nextTick(() => {
      if (elementRef && elementRef.value) {
        returnHeight.value = windowHeight - elementRef.value.offsetHeight - offset;
      } else {
        returnHeight.value = windowHeight - offset;
      }
    });
  }
  return {
    returnHeight,
    redoHeight,
  };
}
